package com.dc.base.livedata;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 冰柠檬dc
 *
 * 注册订阅：
 * LiveDataBus.get().with("tag", String.class).observe(this, new Observer<String>() {
 *      @Override
 *      public void onChanged(@Nullable String s) {
 *      }
 * });
 *
 * 发送消息：
 * LiveDataBus.get().with("tag").setValue(str);
 */
public class LiveDataBus {

    private final Map<String, UnPeekLiveData<Object>> bus;

    private LiveDataBus() {
        bus = new HashMap<>();
    }

    private static class SingletonHolder {
        private static final LiveDataBus DEFAULT_BUS = new LiveDataBus();
    }

    public static LiveDataBus get() {
        return SingletonHolder.DEFAULT_BUS;
    }

    public <T> UnPeekLiveData<T> with(String key, Class<T> type) {
        if (!bus.containsKey(key)) {
            bus.put(key, new UnPeekLiveData<>());
        }
        return  (UnPeekLiveData<T>)bus.get(key);
    }

    public UnPeekLiveData<Object> with(String key) {
        return with(key, Object.class);
    }
}
